package pow

import (
	"Dome/tools"
	"bytes"
	"math/big"
	"strconv"
)

const BITS = 15

type ProofOfWork struct {
	//Block *block.Block //给哪个区块工作
	PrevHash []byte
	TimeStamp int64
	Data []byte
	Target *big.Int //系统给定的hash值
}

func NewPow(data []byte,timeStamp int64,prevHash []byte)*ProofOfWork{
	//创建大整数类型变量
	target := big.NewInt(1)//1
	target = target.Lsh(target,255-BITS)

	pow := ProofOfWork{
		PrevHash: prevHash,
		TimeStamp: timeStamp,
		Data: data,
		Target: target,
	}
	return &pow
}
//计算随机数
func(pow *ProofOfWork)Run()([]byte,int64){
	var nonce int64
	nonce = 0

	timeByte := []byte(strconv.FormatInt(pow.TimeStamp,10))
	//转换 把[]byte 转成 大整数类型
	num := big.NewInt(0)
	for{
		nonceByte := []byte(strconv.FormatInt(nonce, 10))
		hashByte := bytes.Join([][]byte{pow.PrevHash,pow.Data,timeByte,nonceByte},[]byte{})
		hash := tools.SetHash(hashByte)
		//fmt.Println("正在寻找nonce，当前nonce为",nonce)
		num = num.SetBytes(hash)
		if(num.Cmp(pow.Target) == -1){
			return hash,nonce
		}
		nonce++
	}
	//if(a < target){
	//
	//}
	//pow.Target
	return nil,0
}
